#
#   main.py
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; version 2 of the License.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   Copyright
#   Author: Nicholas F. Hoover
#   Contributors: Salvatore S. Gionfriddo
#   Created: 2007.06.16
#   Last Modified: 2007.07.25
#

import pygame, os, pickle
import Messages, EventHandler, hud, Mission
from Options import Options
from Game import Game
from ResourceManager import ResourceManager
from EventHandler import GameEventHandler
from MenuSystem import MenuSystem

def main():
   m = Main()
   m.go()

class Main(object):

   WINDOW_TITLE = 'Evil Greg VS. The 8 Year Olds'

   DEFAULT_MISSION = "INTRO"

   def __init__(self):
      pygame.init()
      pygame.mixer.init()
      self.options = Options('options.ini')
      self.options.readOptionsFile()
      
      #setup up window
      if Options.VIDEO['FULLSCREEN']: useFullscreen = pygame.FULLSCREEN
      else: useFullscreen = 0

      self.screen = pygame.display.set_mode(Options.VIDEO['RESOLUTION'], useFullscreen)
      pygame.display.set_caption(self.WINDOW_TITLE)
      pygame.mouse.set_visible(False)

      #setup the splash screen
      self.rManager = ResourceManager()
      self.screen.blit(self.rManager.getSplashScreen(),(0,0))
      Messages.printSubtitle(self.screen)
      Messages.printLoading(self.screen)
      pygame.display.flip()
      self.changeSong(ResourceManager.INTRO_SONG)

      #load resources
      self.rManager.loadResources()
      Messages.printDoneLoading(self.screen)
      pygame.display.flip()
      EventHandler.waitForKeyOrQuit(Options.CONTROLS['ENTER'])
      
      self.highScore = {}
      self.loadHighScores()
      self.mission = self.DEFAULT_MISSION
      

      self.game = Game(self.screen, self.rManager, Mission.MISSIONS[self.mission])
      self.menu = MenuSystem(self.screen, self.options, self.rManager.getMenuSplash(), self.setMission, self.highScore)

   def go(self):
      while True:
         self.menu.display()
         
         self.changeSong(ResourceManager.GAME_SONG)
         self.game.background.draw()
         self.game.mainLoop()
         self.stopGame()
         self.game.reset()

   def setMission(self, mission):
      self.mission = mission
      self.game.setMission(Mission.MISSIONS[self.mission])


   def stopGame(self):
      self.game.tintScreen()
      self.changeSong(ResourceManager.DEAD_SONG, 0)
      scoreDetails = self.game.getScore()
      score = self.calculateScore(scoreDetails)
      self.testAndSetHighScore(score)
      Messages.printGameOver(self.screen, score, self.highScore[self.mission], scoreDetails, self.game.win)

      pygame.display.flip()
      EventHandler.waitForKeyOrQuit(Options.CONTROLS['ENTER'])
      self.changeSong(ResourceManager.INTRO_SONG)

   def changeSong(self, newSong, loop = -1):
      pygame.mixer.music.stop()
      self.rManager.loadSong(newSong)
      if Options.SOUND['MUSIC_ON']:
         pygame.mixer.music.play(loop)

   def calculateScore(self, scoreDetails):
      score = 0
      for entry in scoreDetails:
         score += (entry[0] * entry[1])
      return score


   def loadHighScores(self):
      # attempt to de-pickle
      try:
          raw_score_dat = file(os.path.join('data', 'user', 'score') + '.dat')
          self.highScore = pickle.load(raw_score_dat)
          raw_score_dat.close()
      except:
          # if failed create new high score
          pass
      for mission in Mission.MISSIONS:
          if not (mission in self.highScore):
            self.highScore.update([(mission, 0)])
      
      
   def testAndSetHighScore(self, score):
      if score > self.highScore[self.mission]:
         self.highScore[self.mission] = score

         try:
            raw_score_dat = open(os.path.join('data', 'user', 'score') + '.dat', 'w')
            pickle.dump(self.highScore, raw_score_dat)
            raw_score_dat.close()
         except IOError, e:
            print "File Error!", e
